#include "common.hpp"
#include "log.hpp"

Init init;
int main(){
    //1.生成共享内存键值
    key_t shmkey = ftok(PATH_NAME, PROJ_ID);
    if(shmkey == -1)
    {
        perror("ftok");
        exit(errno);
    }
    PrintLog("create shmkey sucess!", DEBUG);
    printf("shmkey: %#x\n", shmkey); //16进制带前缀输出

    //2.创建共享内存
    int shmid = shmget(shmkey, SHM_SIZE, IPC_CREAT | IPC_EXCL | MODE);
    if(shmid == -1)
    {
        perror("shmget");
        exit(errno);
    }
    PrintLog("create share memory sucess!", DEBUG);
    printf("shmid: %d\n", shmid);

    //3.将共享内存区域映射到进程地址空间中
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (char*)-1)
    {
        perror("shmat");
        exit(errno);
    }
    PrintLog("attach share memory sucess!", DEBUG);
    printf("shmaddr: %p\n", shmaddr);

    //4.进程间通信
    // sleep(10);
    int fd = Openfifo(FIFO_PATH, O_RDONLY);
    while(true)
    {
        Wait(fd);
        printf("%s\n", shmaddr);
        if(strcmp(shmaddr, "quit") == 0)
        {
            break;
        }
        // sleep(1);
    }
    Closefifo(fd);

    //5.解除共享内存区域映射
    int ret = shmdt(shmaddr);
    if(ret == -1)
    {
        perror("shmdt");
        exit(errno);
    }
    PrintLog("detach share memory sucess!", DEBUG);
    // sleep(10);

    //6.删除共享内存
    ret = shmctl(shmid, IPC_RMID, nullptr);
    if(ret == -1)
    {
        perror("shmctl");
        exit(errno);
    }
    PrintLog("delete share memory sucess!", DEBUG);


    return 0;
}